package me.flyray.gate.utils;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import me.flyray.cache.CacheProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author Mu
 * @Description: 白名单工具类
 */
public class AccessIpListUtils {
	@Autowired
	private static RedisTemplate redisTemplate;
	/**
	 * 获取访问IP地址
	 */
	public static String getIpAdrress(HttpServletRequest request) {
		String Xip = request.getHeader("X-Real-IP");
		String XFor = request.getHeader("X-Forwarded-For");
		if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			int index = XFor.indexOf(",");
			if (index != -1) {
				return XFor.substring(0, index);
			} else {
				return XFor;
			}
		}
		XFor = Xip;
		if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
			return XFor;
		}
		if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
			XFor = request.getRemoteAddr();
		}
		return XFor;
	}

	/**
	 * 校验IP白名单
	 * 
	 */
	public static boolean checkIpList(String realIp) {
		List<Map<String, Object>> redisIplist = (List<Map<String, Object>>) CacheProvider.get("i_flyray-admin:ipList",List.class);
		boolean isexist = false;
		try {
			if (null != redisIplist && redisIplist.size() > 0) {
				for (Map<String, Object> ipmap : redisIplist) {
					if (realIp.equals(ipmap.get("ip"))) {
						isexist = true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return isexist;
		}
		return isexist;
	}

}
